import axios from 'axios';
import { Notification } from 'element-ui';
import { getToken } from '@/utils/auth';
/**
 * 自定义Axios实例
 */
const AJAX = axios.create({
  baseURL: '',
  timeout: 30000,
  withCredentials: true,
});

// 添加请求拦截器
AJAX.interceptors.request.use(
  function(config) {
    // 在发送请求之前做些什么
    // if (process.env.NODE_ENV === 'development') {
    //     config.url = `http://${location.host}` + config.url; // 自定义反向代理，可以在demo阶段打开看下请求效果
    // }
    return config;
  },
  function(error) {
    // 对请求错误做些什么
    return Promise.reject(error);
  }
);

// 添加响应拦截器
AJAX.interceptors.response.use(
  function(response) {
    // 对响应数据做点什么
    if (!response.data.status || response.data.status === 200) {
      return response.data;
    } else {
      Notification({
        message: response.data.message,
        type: 'error',
      });
      return;
    }
  },
  function(error) {
    console.log(error);
    // 对响应错误做点什么，比如400、401、402等等
    if (error && error.response) {
      console.log(error.response);
    }
    return Promise.reject(error);
  }
);

// 定义对外Get、Post、File请求
export default {
  get(url, param = {}) {
    return AJAX.get(url, {
      params: param,
      headers: {
        Authorization: getToken(),
        authGroup: 405,
        'Cache-Control': 'public',
      },
    });
  },
  post(url, param = null) {
    return AJAX.post(url, param, {
      headers: {
        Authorization: getToken(),
        authGroup: 405,
      },
    });
  },
  put(url, param = null) {
    return AJAX.put(url, param, {
      headers: {
        Authorization: getToken(),
        authGroup: 405,
      },
    });
  },
  file(url, param = null, headers = {}) {
    return AJAX.post(url, param, {
      headers: Object.assign(
        {
          Accept: '*/*',
          'Content-Type': 'multipart/form-data',
          authGroup: 405,
        },
        headers
      ),
    });
  },
  delete(url, param = null, headers = {}) {
    return AJAX.delete(url, {
      param,
      headers: Object.assign(
        {
          'Content-Type': 'multipart/form-data',
          Authorization: getToken(),
          authGroup: 405 || '-1',
        },
        headers
      ),
    });
  },
};
